import numpy as np
from pykrige.ok import OrdinaryKriging

def idw_interpolation(x, y, z, xi, yi, power=2):
    dist = np.sqrt((x - xi) ** 2 + (y - yi) ** 2)
    dist[dist == 0] = 1e-10  # 防止除零
    weights = 1 / (dist ** power)
    return np.sum(weights * z) / np.sum(weights)

def idw_batch(df):
    preds = []
    coords = df[["lon", "lat"]].values
    values = df["pre"].values
    for i in range(len(df)):
        x = np.delete(coords[:, 0], i)
        y = np.delete(coords[:, 1], i)
        z = np.delete(values, i)
        xi, yi = coords[i]
        pred = idw_interpolation(x, y, z, xi, yi)
        preds.append(pred)
    return preds

def kriging_batch(df):
    preds = []
    stds = []
    coords = df[["lon", "lat"]].values
    values = df["pre"].values
    for i in range(len(df)):
        x = np.delete(coords[:, 0], i)
        y = np.delete(coords[:, 1], i)
        z = np.delete(values, i)
        xi, yi = coords[i]
        try:
            OK = OrdinaryKriging(x, y, z, variogram_model="linear", verbose=False, enable_plotting=False)
            z_val, z_std = OK.execute("points", [xi], [yi])
            preds.append(float(z_val[0]))
            stds.append(float(z_std[0]))
        except:
            preds.append(np.nan)
            stds.append(np.nan)
    return preds, stds


# -------------------------------
# 度分秒转换为度（十进制度）
def dms_to_deg(dms_str):
    dms = dms_str.strip()
    d = int(dms[:-4])
    m = int(dms[-4:-2])
    s = int(dms[-2:])
    return d + m / 60 + s / 3600

# -------------------------------